package com.movitech.mobile.cz.base.supplier.bizservice.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.movitech.mobile.cz.base.bizconfig.entity.SSuppliersCategory;
import com.movitech.mobile.cz.base.bizconfig.entity.ext.ExtSSuppliersCategoryTemplate;
import com.movitech.mobile.cz.base.bizconfig.mapper.ext.ExtSSuppliersCategoryMapper;
import com.movitech.mobile.cz.base.bizconfig.mapper.ext.ExtSSuppliersCategoryTemplateMapper;
import com.movitech.mobile.cz.base.bizconfig.service.SSuppliersCategoryService;
import com.movitech.mobile.cz.base.common.aop.ServiceThrowable;
import com.movitech.mobile.cz.base.common.bpm.BpmUtil;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.*;
import com.movitech.mobile.cz.base.common.utils.IdGen;
import com.movitech.mobile.cz.base.modules.config.*;
import com.movitech.mobile.cz.base.modules.controller.RestReturnResult;
import com.movitech.mobile.cz.base.purchase.entity.ext.ExtWFlowForm;
import com.movitech.mobile.cz.base.sessionuser.SessionUserVo;
import com.movitech.mobile.cz.base.supplier.bizservice.SSuppliersEvaluationService;
import com.movitech.mobile.cz.base.supplier.bizvo.*;
import com.movitech.mobile.cz.base.supplier.entity.*;
import com.movitech.mobile.cz.base.supplier.entity.ext.*;
import com.movitech.mobile.cz.base.supplier.mapper.SEvaluationImproveHisMapper;
import com.movitech.mobile.cz.base.supplier.mapper.SEvaluationMapper;
import com.movitech.mobile.cz.base.supplier.mapper.ext.*;
import com.movitech.mobile.cz.base.supplier.service.*;
import com.movitech.mobile.cz.base.sys.entity.SAttachment;
import com.movitech.mobile.cz.base.sys.mapper.SAttachmentMapper;
import com.movitech.mobile.cz.base.util.UserUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.Session;
import java.text.MessageFormat;
import java.util.*;

/**
 * Created by Blue.Xia on 2018/3/6.
 */
@Service("sSuppliersEvaluationService")
public class SSuppliersEvaluationServiceImpl extends ServiceImpl<SEvaluationMapper, SEvaluation> implements SSuppliersEvaluationService {

    @Autowired
    private ExtSEvaluationMapper extSEvaluationMapper;

    @Autowired
    private SEvaluationMapper sEvaluationMapper;

    @Autowired
    private ExtSEvaluationPersonMapper extSEvaluationPersonMapper;

    @Autowired
    private ExtSEvaluationPerformScoresMapper extSEvaluationPerformScoresMapper;

    @Autowired
    private ExtSSuppliersCategoryTemplateMapper extSSuppliersCategoryTemplateMapper;

    @Autowired
    private ExtSHistoryCommentMapper extSHistoryCommentMapper;

    @Autowired
    private ExtSSuppliersCategoryMapper extSSuppliersCategoryMapper;

    @Autowired
    private SEvaluationPersonService sEvaluationPersonService;
    @Autowired
    private SEvaluationService sEvaluationService;

    @Autowired
    private SEvaluationPerformScoresService sEvaluationPerformScoresService;

    @Autowired
    private SHistoryCommentService sHistoryCommentService;

    @Autowired
    private SMyDealsService sMyDealsService;

    @Autowired
    private SCommentConfigService sCommentConfigService;

    @Autowired
    private SSuppliersRankService sSuppliersRankService;

    @Autowired
    private SSuppliersService sSuppliersService;

    @Autowired
    private SSuppliersCategoryService sSuppliersCategoryService;

    @Autowired
    private SSuppliersMbsContactsService sSuppliersMbsContactsService;

    @Autowired
    private SSuppliersLastThreeAchieveService sSuppliersLastThreeAchieveService;

    @Autowired
    private SEvaluationTemplateService sEvaluationTemplateService;

    @Autowired
    private SEvaluationTemplateDetailsService sEvaluationTemplateDetailsService;

    @Autowired
    private SSuppliersRankScoresService sSuppliersRankScoresService;

    @Autowired
    private SSuppliersRankAuditsService sSuppliersRankAuditsService;

    @Autowired
    private SSuppliersRankAuditsDetailService sSuppliersRankAuditsDetailService;
    @Autowired
    private SAttachmentMapper sAttachmentMapper;
    @Autowired
    private ExtSEvaluationImproveHisMapper extSEvaluationImproveHisMapper;
    @Autowired
    private SEvaluationImproveHisMapper sEvaluationImproveHisMapper;
    @Autowired
    @Qualifier("bpmUtil")
    private BpmUtil bpmUtil;

    /**
     * 供方评估列表
     *
     * @param evaluationListRequestVO
     * @return
     */
//    @Override
//    public PageCode findEvaluationList(EvaluationListRequestVO evaluationListRequestVO) {
//        PageCode pageCode = new PageCode(evaluationListRequestVO.getPageNumber(), evaluationListRequestVO.getPageSize());
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
//        map.put("pageSize", pageCode.getPageSize());
//
//        map.put("contractName", evaluationListRequestVO.getContractName());
//        map.put("supplierName", evaluationListRequestVO.getSupplierName());
//        map.put("regionalCompanyName", evaluationListRequestVO.getRegionalCompanyName());
//        map.put("projectCompanyName", evaluationListRequestVO.getProjectCompanyName());
//        map.put("evaluationYear", evaluationListRequestVO.getEvaluationYear());
//        map.put("evaluationSubType", evaluationListRequestVO.getEvaluationSubType());
//
//        if (EvaluationStaticEnum.DURING_EVALUTED.equals(evaluationListRequestVO.getEvaluationStatic())) {//履约过程已评估
//            map.put("evaluationType", 1);
//            map.put("evaluationStatus", "1,2,3,4,5");
//        } else if (EvaluationStaticEnum.AFTER_EVALUTED.equals(evaluationListRequestVO.getEvaluationStatic())) {//履约后已评估
//            map.put("evaluationType", 2);
//            map.put("evaluationStatus", "6,7");
//        } else if (EvaluationStaticEnum.AFTER_TO_EVALUTE.equals(evaluationListRequestVO.getEvaluationStatic())) {//履约后程待评估
//            map.put("evaluationType", 2);
//            map.put("evaluationStatus", "6,7");
//        } else {//履约过程待评估
//            map.put("evaluationType", 1);
//            map.put("evaluationStatus", "1,2,3,4,5");
//        }
//        if (evaluationListRequestVO.getEvaluationStatus() != null) {
//            map.put("evaluationStatus", evaluationListRequestVO.getEvaluationStatus());
//        }
//        Integer count = extSEvaluationMapper.findEvaluationListCount(map);
//        pageCode.setCount(count == null ? 0 : count);
//        List<ExtSSuppliers> ls = extSEvaluationMapper.findEvaluationList(map);
//        pageCode.setList(ls);
//        return pageCode;
//    }

    /**
     * 评估详情
     *
     * @param evaluationId
     * @return ExtSEvaluation
     */
    @Override
    public ExtSEvaluation getSEvaluationById(String evaluationId) {

    	try{

    		if(StringUtils.isBlank(evaluationId)){
    			throw new RuntimeException("传参为空", new ServiceThrowable());
    		}

    		ExtSEvaluation extSEvaluation = extSEvaluationMapper.getSEvaluationById(evaluationId);
            if (extSEvaluation != null) {
                //评估人选择
                EvaluationPersonFindRequest evaluationPersonFindRequest = new EvaluationPersonFindRequest();
                evaluationPersonFindRequest.setEvaluationId(extSEvaluation.getId());
                List<ExtSEvaluationPerson> extSEvaluationPersonList =
                        extSEvaluationPersonMapper.findEvaluationPersonList(evaluationPersonFindRequest);
                extSEvaluation.setExtSEvaluationPersonList(extSEvaluationPersonList);

                //履约评分汇总
                SEvaluationPerformScoresFindRequest sEvaluationPerformScoresFindRequest = new SEvaluationPerformScoresFindRequest();
                sEvaluationPerformScoresFindRequest.setEvaluationId(extSEvaluation.getId());
                List<ExtSEvaluationPerformScores> extSEvaluationPerformScoresList =
                        extSEvaluationPerformScoresMapper.findEvaluationPerformScoresList(sEvaluationPerformScoresFindRequest);
                extSEvaluation.setExtSEvaluationPerformScoresList(extSEvaluationPerformScoresList);

                //审批记录
                SHistoryCommentFindRequest sHistoryCommentFindRequest = new SHistoryCommentFindRequest();
                sHistoryCommentFindRequest.setRelatedId(extSEvaluation.getId());
                List<ExtSHistoryComment> sHistoryCommentList = extSHistoryCommentMapper.findHistoryCommentList(sHistoryCommentFindRequest);
                extSEvaluation.setSHistoryCommentList(sHistoryCommentList);
                //改进历史
                List<ExtSEvaluationImproveHis> extSEvaluationImproveHis = extSEvaluationImproveHisMapper.findAllBySEvaluaId(evaluationId);
                extSEvaluation.setExtSEvaluationImproveHis(extSEvaluationImproveHis);
                return extSEvaluation;
            }

    	}catch(Exception e){
    		e.printStackTrace();
    		throw new RuntimeException(e.getMessage(), e.getCause());
    	}

        return null;
    }

    @Override
    public ExtSEvaluation getImproveDetailById(String evaluationId) {
        try{

            LicenseUtil.INSTANCE.validate();
            if(StringUtils.isBlank(evaluationId)){
                throw new RuntimeException("传参为空", new ServiceThrowable());
            }

            ExtSEvaluation extSEvaluation = extSEvaluationMapper.getSEvaluationById(evaluationId);
            if (extSEvaluation != null) {
                //评估人选择
                EvaluationPersonFindRequest evaluationPersonFindRequest = new EvaluationPersonFindRequest();
                evaluationPersonFindRequest.setEvaluationId(extSEvaluation.getId());
                List<ExtSEvaluationPerson> extSEvaluationPersonList =
                        extSEvaluationPersonMapper.findEvaluationPersonList(evaluationPersonFindRequest);
                extSEvaluation.setExtSEvaluationPersonList(extSEvaluationPersonList);

                //履约评分汇总
                SEvaluationPerformScoresFindRequest sEvaluationPerformScoresFindRequest = new SEvaluationPerformScoresFindRequest();
                sEvaluationPerformScoresFindRequest.setEvaluationId(extSEvaluation.getId());
                List<ExtSEvaluationPerformScores> extSEvaluationPerformScoresList =
                        extSEvaluationPerformScoresMapper.findEvaluationPerformScoresList(sEvaluationPerformScoresFindRequest);
                extSEvaluation.setExtSEvaluationPerformScoresList(extSEvaluationPerformScoresList);

                return extSEvaluation;
            }

        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

        return null;
    }

    @Override
    public ExtSEvaluation getSEvaluationDealById(String evaluationId) {
        if(StringUtils.isBlank(evaluationId)){
            throw new RuntimeException("传参为空", new ServiceThrowable());
        }
        ExtSEvaluation extSEvaluation = extSEvaluationMapper.getSEvaluationById(evaluationId);
        if (extSEvaluation != null) {

            //履约评分汇总
            SEvaluationPerformScoresFindRequest sEvaluationPerformScoresFindRequest = new SEvaluationPerformScoresFindRequest();
            sEvaluationPerformScoresFindRequest.setEvaluationId(extSEvaluation.getId());
            sEvaluationPerformScoresFindRequest.setUserId(UserUtils.getCurrentUserId());
            //sEvaluationPerformScoresFindRequest.setUserId("MG1930");
            List<ExtSEvaluationPerformScores> extSEvaluationPerformScoresList =
                    extSEvaluationPerformScoresMapper.findEvaluationPerformScoresList(sEvaluationPerformScoresFindRequest);
            extSEvaluation.setExtSEvaluationPerformScoresList(extSEvaluationPerformScoresList);
        }
        return extSEvaluation;
    }

    /**
     * 评估创建数据查询
     *
     * @param evaluationLaunchDataRequest
     * @return ExtSEvaluation
     */
    @Override
    public ExtSEvaluation getLaunchEvaluationData(EvaluationLaunchDataRequest evaluationLaunchDataRequest) {
    	try{
    		if(evaluationLaunchDataRequest == null){
    			throw new RuntimeException("传参为空", new ServiceThrowable());
    		}
    		Integer year = Integer.parseInt(DateUtils.format(DateUtils.getNow(),"yyyy"));
            ExtSEvaluation extSEvaluation = null;
    		if(evaluationLaunchDataRequest.getEvaluationType() == 1&&StringUtils.isNotEmpty(evaluationLaunchDataRequest.getEvaluationId())){
                extSEvaluation = extSEvaluationMapper.getSEvaluationById(evaluationLaunchDataRequest.getEvaluationId());

            }else if(evaluationLaunchDataRequest.getEvaluationType() == 2){
                extSEvaluation = new ExtSEvaluation();
                ExtSSuppliersLastThreeAchieve extSSuppliersLastThreeAchieve = sSuppliersLastThreeAchieveService.findExtById(evaluationLaunchDataRequest.getCid());

                extSEvaluation.setRegionalCompanyName(extSSuppliersLastThreeAchieve.getRegionalCompanyName());
                extSEvaluation.setRegionalCompanyIds(extSSuppliersLastThreeAchieve.getRegionalCompanyId());
                extSEvaluation.setProjectCompanyName(extSSuppliersLastThreeAchieve.getProjectName());
                extSEvaluation.setProjectIds(extSSuppliersLastThreeAchieve.getCooperativeProjectId());

                extSEvaluation.setCompanyName(extSSuppliersLastThreeAchieve.getSuppliersName());
                extSEvaluation.setSupplierId(extSSuppliersLastThreeAchieve.getSuppliersId());

                String supplierCategoryIds = "";
                if(StringUtils.isNotEmpty(extSSuppliersLastThreeAchieve.getSuppliersId())){
                    SSuppliers sSuppliers = sSuppliersService.getById(extSSuppliersLastThreeAchieve.getSuppliersId());
                    if(sSuppliers!=null){
                        supplierCategoryIds = sSuppliers.getSupplierServiceCategoryIds();
                    }
                }
                extSEvaluation.setSupplierCategoryIds(supplierCategoryIds);
                extSEvaluation.setEvaluationType(2);
                extSEvaluation.setEvaluationSubType(3);
                extSEvaluation.setContractId(extSSuppliersLastThreeAchieve.getId());
                extSEvaluation.setContractName(extSSuppliersLastThreeAchieve.getContactName());
                extSEvaluation.setEvaluationStatus(1);
                //extSEvaluation.setHandleUserId();
                extSEvaluation.setEvaluationYear(year);
    		}

            LicenseUtil.INSTANCE.validate();
//            //审批记录
//            SHistoryCommentFindRequest sHistoryCommentFindRequest = new SHistoryCommentFindRequest();
//            sHistoryCommentFindRequest.setRelatedId(extSEvaluation.getId());
//            List<ExtSHistoryComment> sHistoryCommentList = extSHistoryCommentMapper.findHistoryCommentList(sHistoryCommentFindRequest);
//            extSEvaluation.setSHistoryCommentList(sHistoryCommentList);

            return extSEvaluation;
    	}catch(Exception e){
    		e.printStackTrace();
    		throw new RuntimeException(e.getMessage(), e.getCause());
    	}

    }

    /**
     * 评估创建数据保存
     *
     * @param evaluationSaveLaunchDataRequest
     * @return ExtSEvaluation
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public boolean saveLaunchEvaluationData(ExtSEvaluation evaluationSaveLaunchDataRequest) throws RuntimeException {
    	try{
    		if(evaluationSaveLaunchDataRequest == null){
    			throw new RuntimeException("传参为空", new ServiceThrowable());
    		}
            if(evaluationSaveLaunchDataRequest.getEvaluationType()==1){
            }else{
                if(evaluationSaveLaunchDataRequest.getEvaluationType()==null){//后评估
                    evaluationSaveLaunchDataRequest.setEvaluationType(2);
                }
                if(StringUtils.isEmpty(evaluationSaveLaunchDataRequest.getId())){
                    evaluationSaveLaunchDataRequest.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, true);
                }
            }
            LicenseUtil.INSTANCE.validate();
            //evaluationSaveLaunchDataRequest.setEvaluationEndTime(DateUtils.addMonth(DateUtils.getNow()));
            evaluationSaveLaunchDataRequest.setEvaluationEndTime(DateUtils.getDayPlus(30));
    		evaluationSaveLaunchDataRequest.setEvaluationTime(DateUtils.getNow());
            evaluationSaveLaunchDataRequest.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_STATUS_2.getCode());
            sEvaluationService.insertOrUpdate(evaluationSaveLaunchDataRequest);

            // 供方评估人员数据保存
            sEvaluationPersonService.updateSEvaluationPerson(evaluationSaveLaunchDataRequest.getId(),evaluationSaveLaunchDataRequest.getExtSEvaluationPersonList());

            sEvaluationPerformScoresService.syncSEvaluationPerformScores(evaluationSaveLaunchDataRequest.getId(),evaluationSaveLaunchDataRequest.getExtSEvaluationPerformScoresList(),
                    evaluationSaveLaunchDataRequest.getExtSEvaluationPersonList());

            //保存日志
            boolean historyCommentFlag = saveSHistoryComment(evaluationSaveLaunchDataRequest);
            if(!historyCommentFlag){
                return false;
            }

            //保存我的代办
            List<ExtSEvaluationPerson> extSEvaluationPersonList = evaluationSaveLaunchDataRequest.getExtSEvaluationPersonList();
            if(extSEvaluationPersonList != null && extSEvaluationPersonList.size() >  0){
                saveSMyDeals(evaluationSaveLaunchDataRequest, extSEvaluationPersonList);
            }
    		return true;
    	}catch(Exception e){
    		e.printStackTrace();
    		throw new RuntimeException(e.getMessage(), e.getCause());
    	}

    }

    @Override
    public void submitEvaluationScore(ExtSEvaluation evaluationSaveLaunchDataRequest) {
        try {
            List<ExtSEvaluationPerformScores> extSEvaluationPerformScoresList = evaluationSaveLaunchDataRequest.getExtSEvaluationPerformScoresList();
            if(extSEvaluationPerformScoresList != null && extSEvaluationPerformScoresList.size() > 0){
                //履约评分打分
                List<SEvaluationPerformScores> SEvaluationPerformScoresList = null;
                SEvaluationPerformScoresList = ListObjCopyUtil.copyTo(extSEvaluationPerformScoresList, SEvaluationPerformScores.class);
                sEvaluationPerformScoresService.updateBatchById(SEvaluationPerformScoresList);


                LicenseUtil.INSTANCE.validate();
                //更新待办、更新供方评估总得分
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("relatedId", evaluationSaveLaunchDataRequest.getId());
                map.put("dealType", DealTypeEnum.SUPPLIERS.getCode());
                map.put("dealSubType", MyDealSubTypeEnum.SUPPLIERS_EVALUATION.getCode());
                map.put("doneFlag", CommonConstants.UNDONG_FLAG);
                List<ExtSMyDeals> myDealList = sMyDealsService.getMyDealListByParams(map);
                if(myDealList != null && myDealList.size() == 1){

                    SEvaluationPerformScoresFindRequest sEvaluationPerformScoresFindRequest = new SEvaluationPerformScoresFindRequest();
                    sEvaluationPerformScoresFindRequest.setEvaluationId(evaluationSaveLaunchDataRequest.getId());
                    List<ExtSEvaluationPerformScores> list =
                            extSEvaluationPerformScoresMapper.findEvaluationPerformScoresList(sEvaluationPerformScoresFindRequest);

                    if(list != null && list.size() > 0){
                        double totalScore = 0;
                        for(ExtSEvaluationPerformScores performScore : list){
                            Integer weight =  Integer.parseInt(performScore.getEvaluationWeight());
                            totalScore += weight/5*performScore.getScores();
                        }
                        ExtSEvaluation sEvaluationDB = extSEvaluationMapper.getSEvaluationById(evaluationSaveLaunchDataRequest.getId());
                        sEvaluationDB.setEvaluationScore(totalScore);
                        sEvaluationDB.setInitEvaluationScore(totalScore);
                        //待审批
                        sEvaluationDB.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_STATUS_7.getCode());
                        sEvaluationDB.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);
                        sEvaluationMapper.updateById(sEvaluationDB);

                        //sSuppliersRankScoresService.insert(convertSEvaluation2sSuppliersRankScores(sEvaluationDB));
                    }
                }

                SMyDeals sMyDeals = new SMyDeals();
                sMyDeals.setUserId(UserUtils.getCurrentUserId());
                //sMyDeals.setUserId("MG1930");
                sMyDeals.setRelatedId(evaluationSaveLaunchDataRequest.getId());
                sMyDeals.setDealType(DealTypeEnum.SUPPLIERS.getCode());
                sMyDeals.setDealSubType(MyDealSubTypeEnum.SUPPLIERS_EVALUATION.getCode());
                sMyDealsService.updateSMyDealsByEntity(sMyDeals);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ExtSSuppliersRankScores convertSEvaluation2sSuppliersRankScoresProject(ExtSEvaluation extSEvaluation){
        ExtSSuppliersRankScores sSuppliersRankScores = new ExtSSuppliersRankScores();
        sSuppliersRankScores.setEvaluationType(3);
        sSuppliersRankScores.setRegionalCompanyName(extSEvaluation.getRegionalCompanyName());
        sSuppliersRankScores.setProjectName(extSEvaluation.getProjectName());
        sSuppliersRankScores.setContractName(extSEvaluation.getContractName());
        sSuppliersRankScores.setEvaluationTime(extSEvaluation.getEvaluationTime());
        sSuppliersRankScores.setEvaluationId(extSEvaluation.getId());
        //sSuppliersRankScores.setEvaluationScore(extSEvaluation.getEvaluationScore());
        sSuppliersRankScores.setBaseFeilds(UserUtils.getCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
        return sSuppliersRankScores;
    }

    @Override
    public List<SSuppliersLastThreeAchieve> findSimByname(String name) {
        if(StringUtils.isEmpty(name)){
            return null;
        }
        return sSuppliersLastThreeAchieveService.findSimListByName(name);
    }


    private boolean saveSMyDeals(ExtSEvaluation sEvaluation, List<ExtSEvaluationPerson> extSEvaluationPersonList) {
        Map<String,String > map = new HashMap<>();
        LicenseUtil.INSTANCE.validate();
    	for(ExtSEvaluationPerson person : extSEvaluationPersonList){
            if(map.get(person.getUserId())==null){
                SMyDeals sMyDeals = new SMyDeals();
                sMyDeals.setUserId(person.getUserId());
                sMyDeals.setDealType(DealTypeEnum.SUPPLIERS.getCode());
                sMyDeals.setDealSubType(MyDealSubTypeEnum.SUPPLIERS_EVALUATION  .getCode());
                sMyDeals.setRelatedId(sEvaluation.getId());
                if(sEvaluation.getEvaluationType()==1){
                    sMyDeals.setActionType(ActionTypeEnum.SUPPLIERS_EVALUATION.getCode());
                }else{
                    sMyDeals.setActionType(ActionTypeEnum.SUPPLIERS_EVALUATION_END.getCode());
                }

                sMyDeals.setDealTitle(MessageFormat.format(sCommentConfigService.getValueByCode(CommentConfigEnum.EVALUATION_LAUNCH_ADD_DEAL_TITLE.getCode()),sEvaluation.getCompanyName()));
                sMyDealsService.saveSMyDeals(sMyDeals);
                map.put(person.getUserId(),person.getUserId());
            }
    	}

        return true;
    }

    private boolean saveSHistoryComment(SEvaluation sEvaluation) {
        SHistoryComment sHistoryComment = new SHistoryComment();
        sHistoryComment.setModelType(HistoryCommentModelTypeEnum.HistoryCommentModelType3.getCode());
        sHistoryComment.setRelatedId(sEvaluation.getId());
        sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.EVALUATION_LAUNCH_ADD_HISTORY_COMMENT_NODE_NAME.getCode()));
        //sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.EVALUATION_LAUNCH_ADD_HISTORY_COMMENT_COMMENT_CONTENT.getCode()));
        sHistoryComment.setActionName(sCommentConfigService.getValueByCode(CommentConfigEnum.EVALUATION_LAUNCH_ADD_HISTORY_COMMENT_ACTION_NAME.getCode()));
        sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET_INTERNET.getCode());
        sHistoryComment.setSetupTime(new Date());
        boolean historyCommentFlag = sHistoryCommentService.saveSHistoryComment(sHistoryComment);
        return historyCommentFlag;
    }

    private boolean updateEvaluationData(SEvaluation sEvaluation, EvaluationSaveLaunchDataRequest evaluationSaveLaunchDataRequest) {

        if(evaluationSaveLaunchDataRequest.getContractName() != null){
            sEvaluation.setContractName(evaluationSaveLaunchDataRequest.getContractName());
        }
        if(evaluationSaveLaunchDataRequest.getSupplierId() != null){
            sEvaluation.setSupplierId(evaluationSaveLaunchDataRequest.getSupplierId());
        }
        if(evaluationSaveLaunchDataRequest.getRegionalCompanyIds() != null){
            sEvaluation.setRegionalCompanyIds(sEvaluation.getRegionalCompanyIds());
        }
        if(evaluationSaveLaunchDataRequest.getProjectIds() != null){
            sEvaluation.setProjectIds(sEvaluation.getProjectIds());
        }
        if(evaluationSaveLaunchDataRequest.getEvaluationDesc() != null){
            sEvaluation.setEvaluationDesc(evaluationSaveLaunchDataRequest.getEvaluationDesc());
        }

        if(evaluationSaveLaunchDataRequest.getContractId() != null){
            sEvaluation.setContractId(evaluationSaveLaunchDataRequest.getContractId());
        }

        //评估中
        sEvaluation.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_STATUS_2.getCode());
        sEvaluation.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);
        int i = sEvaluationMapper.updateAllColumnById(sEvaluation);
        return i > 0;
    }

    private List<ExtSEvaluationPerformScores> convert(List<ExtSSuppliersCategoryTemplate> evaluationPerformScoresTemplateList) {
        if (evaluationPerformScoresTemplateList != null) {
            List<ExtSEvaluationPerformScores> list = new ArrayList<ExtSEvaluationPerformScores>();
            for (ExtSSuppliersCategoryTemplate vo : evaluationPerformScoresTemplateList) {
                ExtSEvaluationPerformScores entity = new ExtSEvaluationPerformScores();
                entity.setEvaluationLatitude(vo.getEvaluationDimension());
                entity.setEvaluationIndicator(vo.getEvaluationIndicator());
                entity.setEvaluationWeight(vo.getEvaluationWeight());
                entity.setScoreStandard(vo.getScoreStandard());
                if(vo.getScores() != null){
                    entity.setScores(vo.getScores().doubleValue());
                }
                entity.setEvaluatorUserId(vo.getEvaluatorUserId());
                entity.setEvaluationDepartmentId(vo.getEvaluationDepartmentId());
//                entity.setEvaluatorUserName(vo.getEvaluatorUserName());
//                entity.setEvaluationDepartmentName(vo.getEvaluationDepartmentName());
                list.add(entity);
            }
            return list;
        }
        return null;
    }

    private boolean validateScoreTemplate(Integer evaluationType, String categoryId) throws RuntimeException{

    	SSuppliersCategory sSuppliersCategory = sSuppliersCategoryService.selectById(categoryId);

		if(sSuppliersCategory != null){

			if(evaluationType == 1){//1：履约过程发起评估
				if(sSuppliersCategory.getPerformEvalProcSetFlag() == 1){
					return true;
				}
				return false;
			}

			if(evaluationType == 2){//2：履约后发起评估
				if(sSuppliersCategory.getPerformEvalPostSetFlag() == 1){
					return true;
				}
				return false;
			}

			return false;

		}else{
			throw new RuntimeException("供方分类不存在", new ServiceThrowable());
		}

    }

//    private String getCategoryId(Integer evaluationType) {
//        if (evaluationType == 1 || evaluationType == 2) {//1：履约过程发起评估， 2：履约后发起评估
//            ExtSSuppliersCategory extSSuppliersCategory = new ExtSSuppliersCategory();
//            if (evaluationType == 1) {
//                extSSuppliersCategory.setPerformEvalProcSetFlag(1);
//            } else {
//                extSSuppliersCategory.setPerformEvalPostSetFlag(1);
//            }
//
//            //TODO:待需求确认后，修改
//            List<ExtSSuppliersCategory> suppliersCategory = extSSuppliersCategoryMapper.getSupplierCategoryByFlag(extSSuppliersCategory);
//            if (suppliersCategory != null && suppliersCategory.size() > 0) {
//                return suppliersCategory.get(0).getId();
//            }
//        }
//        return null;
//    }

    /**
     * 评估列表(履约过程、履约后列表)
     */
	@Override
	public RestReturnResult searchEvaluationList(EvaluationListReqVO evaluationListReqVO) {
		try{

            LicenseUtil.INSTANCE.validate();
			if(evaluationListReqVO != null){

				Integer listType = evaluationListReqVO.getListType();

				if(listType != null){

					PageCode pageCode = new PageCode(evaluationListReqVO.getPageNumber(), evaluationListReqVO.getPageSize());

					Map<String, Object> param = new HashMap<String, Object>();
					param.put("evaluationType", evaluationListReqVO.getEvaluationType());
					param.put("contractName", evaluationListReqVO.getContractName());
					param.put("supplierName", evaluationListReqVO.getSupplierName());
					param.put("regionalCompanyId", evaluationListReqVO.getRegionalCompanyId());
					param.put("projectId", evaluationListReqVO.getProjectId());
					param.put("evaluationYear", evaluationListReqVO.getEvaluationYear());
					param.put("evaluationSubType", evaluationListReqVO.getEvaluationSubType());
                    param.put("listType", listType);

                    param.put("evaluationStatus", evaluationListReqVO.getEvaluationStatus());

//					//已评估
//					if(listType == 2){
//						param.put("evaluationStatus", EvaluationStatusEnum.EVALUATION_STATUS_7.getCode());
//					}

					pageCode.setCount(extSEvaluationMapper.findEvaluationListCount(param));

					param.put("currentRecordNum", (pageCode.getPageNo() - 1) * pageCode.getPageSize());
					param.put("pageSize", pageCode.getPageSize());
					param.put("pageFlag", evaluationListReqVO.getPageFlag());
					List<ExtSEvaluation> list = extSEvaluationMapper.findEvaluationList(param);
					pageCode.setList(list);

					return new RestReturnResult(CommonConstants.SUCCESS, pageCode);

				}else{
					throw new RuntimeException("列表类型参数为空", new ServiceThrowable());
				}

			}else{
				throw new RuntimeException("传参为空", new ServiceThrowable());
			}

		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e.getCause());
		}

	}


    @Override
    public List<ExtSEvaluation> exportEvaluationList(EvaluationListReqVO evaluationListReqVO) {
        try{
            Integer listType = evaluationListReqVO.getListType();
            PageCode pageCode = new PageCode(evaluationListReqVO.getPageNumber(), evaluationListReqVO.getPageSize());

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("evaluationType", evaluationListReqVO.getEvaluationType());
            param.put("contractName", evaluationListReqVO.getContractName());
            param.put("supplierName", evaluationListReqVO.getSupplierName());
            param.put("regionalCompanyId", evaluationListReqVO.getRegionalCompanyId());
            param.put("projectId", evaluationListReqVO.getProjectId());
            param.put("evaluationYear", evaluationListReqVO.getEvaluationYear());
            param.put("evaluationSubType", evaluationListReqVO.getEvaluationSubType());
            param.put("listType", listType);
            param.put("evaluationStatus", evaluationListReqVO.getEvaluationStatus());
            param.put("pageFlag", 0);
            List<ExtSEvaluation> list = extSEvaluationMapper.findEvaluationList(param);
            for(ExtSEvaluation extSEvaluation:list){
                if(extSEvaluation.getEvaluationSubType()==1)
                    extSEvaluation.setEvaluationSubTypeName(EvaluationTypeEnum.EVALUATION_MIDDLE_YEAR_1.getDesc());
                else if(extSEvaluation.getEvaluationSubType()==2)
                    extSEvaluation.setEvaluationSubTypeName(EvaluationTypeEnum.EVALUATION_END_YEAR_2.getDesc());
                else {
                    extSEvaluation.setEvaluationSubTypeName(EvaluationTypeEnum.EVALUATION_AFTER_3.getDesc());
                }

            }
            LicenseUtil.INSTANCE.validate();
            return list;
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }

    }

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
	@Override
	public void skipEvaluation(EvaluationSkipReqVO evaluationSkipReqVO) throws RuntimeException{

		try{

            LicenseUtil.INSTANCE.validate();
			if(evaluationSkipReqVO != null){

				SEvaluation sEvaluationDB = sEvaluationMapper.selectById(evaluationSkipReqVO.getEvaluationId());
				if(sEvaluationDB != null){
					sEvaluationDB.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_STATUS_6.getCode());
					sEvaluationDB.setBaseFeilds(UserUtils.getCurrentUserId(), null, CommonConstants.NO_INTEGER, false);

					sEvaluationMapper.updateById(sEvaluationDB);

					SHistoryComment sHistoryComment = new SHistoryComment();
					sHistoryComment.setModelType(HistoryCommentModelTypeEnum.HistoryCommentModelType3.getCode());
					sHistoryComment.setRelatedId(evaluationSkipReqVO.getEvaluationId());
					sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET_INTERNET.getCode());
					sHistoryComment.setNodeName(sCommentConfigService.getValueByCode(CommentConfigEnum.SKIP_EVALUATION_NODE_NAME.getCode()));
					//sHistoryComment.setCommentContent(sCommentConfigService.getValueByCode(CommentConfigEnum.SKIP_EVALUATION_COMMENT_CONTENT.getCode()));
                    sHistoryComment.setCommentContent(evaluationSkipReqVO.getCauseDesc());

                    sHistoryComment.setActionName(sCommentConfigService.getValueByCode(CommentConfigEnum.SKIP_EVALUATION_ACTION_NAME.getCode()));
					sHistoryCommentService.saveSHistoryComment(sHistoryComment);
				}else{
					throw new RuntimeException("不存在此条供方评估记录", new ServiceThrowable());
				}

			}else{
				throw new RuntimeException("传参为空", new ServiceThrowable());
			}

		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e.getMessage(), e.getCause());
		}

	}

    @Override
    public void updateSEvaluationTemplates(String id ) {
        SEvaluationTemplate sEvaluationTemplate = sEvaluationTemplateService.selectById(id);
        if(sEvaluationTemplate.getTemplateStatus()==0){
            sEvaluationTemplate.setTemplateStatus(1);
        }else{
            sEvaluationTemplate.setTemplateStatus(0);
        }
        sEvaluationTemplateService.updateById(sEvaluationTemplate);
    }

    @Override
    public void deleteSEvaluationTemplates(String id ) {
        SEvaluationTemplate sEvaluationTemplate = new SEvaluationTemplate();
        sEvaluationTemplate.setId(id);
        sEvaluationTemplate.setDelFlag(CommonConstants.DEL_FLAG_DELETE);
        sEvaluationTemplateService.updateById(sEvaluationTemplate);
    }

    @Override
    public SupplierRankDtlRspVO supplierRankScoreDtl(SupplierRankDtlReqVo vo) {
        SupplierRankDtlRspVO supplierRankDtlRspVO=new SupplierRankDtlRspVO();
        supplierRankDtlRspVO.setSSuppliersRankScores(converRankScorestoExt(sSuppliersRankScoresService.getByRankId(vo.getId())));
        return supplierRankDtlRspVO;
    }

    @Override
    public SupplierRankDtlRspVO supplierRankDtl(SupplierRankDtlReqVo vo) {
        LicenseUtil.INSTANCE.validate();
        Integer year = vo.getRankYear()==null?Integer.parseInt(DateUtils.format(DateUtils.getNow(),"yyyy")):vo.getRankYear();
        SupplierRankDtlRspVO supplierRankDtlRspVO=new SupplierRankDtlRspVO();
        ExtSSuppliersRank extSSuppliersRank=null;
        String id = vo.getId();
        String supplierId = vo.getSupplierId();
	    if(StringUtils.isNotEmpty(id)){
	        extSSuppliersRank=sSuppliersRankService.getById(id);
            supplierId=extSSuppliersRank.getSuppliersId();
            supplierRankDtlRspVO.setSSuppliersRank(extSSuppliersRank);
        }else{
            extSSuppliersRank = new ExtSSuppliersRank();
            SSuppliers sSuppliers = sSuppliersService.getById(supplierId);
            SSuppliersCategory sSuppliersCategory = sSuppliersCategoryService.selectById(sSuppliers.getSupplierServiceCategoryIds());
            extSSuppliersRank.setSupplierCategoryNames(sSuppliersCategory==null?"":sSuppliersCategory.getCategoryName());
            extSSuppliersRank.setSuppliersName(sSuppliers.getCompanyName());
            extSSuppliersRank.setSuppliersId(sSuppliers.getId());
            extSSuppliersRank.setSupplierCategoryIds(sSuppliers.getSupplierServiceCategoryIds());
        }
	    //过程评估
        Map<String,Object> param = new HashMap<>();
        param.put("evaluationStatus",7);
        param.put("evaluationType",1);
        param.put("evaluationYear",year);
        param.put("supplierId",supplierId);
        List<ExtSEvaluation> sEvaluationProcessList =  extSEvaluationMapper.findEvaluationLevelData(param);

	    if(sEvaluationProcessList!=null&&sEvaluationProcessList.size()>0){
            supplierRankDtlRspVO.setSEvaluationProcessList(sEvaluationProcessList);
        }
        //后评估
        param.put("evaluationType",2);
        List<ExtSEvaluation> sEvaluationPerformanceList =  extSEvaluationMapper.findEvaluationLevelData(param);
	    if(sEvaluationPerformanceList!=null&&sEvaluationPerformanceList.size()>0){
            supplierRankDtlRspVO.setSEvaluationPerformanceList(sEvaluationPerformanceList);
        }

        //工程评估
        Map<String,ExtSEvaluation> dereplication = null;

        int count=0;
        Double score=0.0;
        List<ExtSEvaluation> list = Lists.newArrayList();
        list.addAll(sEvaluationProcessList);
        list.addAll(sEvaluationPerformanceList);
        for(ExtSEvaluation sEvaluation:list){
            if(StringUtils.isEmpty(id)){
                if(dereplication==null){
                    dereplication = Maps.newHashMap();
                }
                dereplication.put(sEvaluation.getProjectIds(),sEvaluation);
            }
            count++;
            score=score+sEvaluation.getEvaluationScore();
        }
        //工程评估数据
        List<ExtSSuppliersRankScores> sSuppliersRankScores = null;
        if(StringUtils.isNotEmpty(id)){
            List<SSuppliersRankScores> sSuppliersRankScores1 = sSuppliersRankScoresService.getByRankId(id);
            sSuppliersRankScores = converRankScorestoExt(sSuppliersRankScores1);

        }else{
            sSuppliersRankScores = Lists.newArrayList();
            if(dereplication!=null)
            for(Map.Entry<String, ExtSEvaluation> entryentries:dereplication.entrySet()){
                sSuppliersRankScores.add(convertSEvaluation2sSuppliersRankScoresProject(entryentries.getValue()));
            }
        }
        int countProject = 0;
        Double scoureProject= 0d;
        for(SSuppliersRankScores suppliersRankScore:sSuppliersRankScores){
            if(suppliersRankScore.getEvaluationScore()==null){
                break;
            }
            countProject++;
            scoureProject+=suppliersRankScore.getEvaluationScore();
        }
        supplierRankDtlRspVO.setSSuppliersRankScores(sSuppliersRankScores);

        //定级数据
        if(count!=0){
            extSSuppliersRank.setProcPostEvalAvgScore(NumberUtils.seekercentage2Double(score/count));
        }else extSSuppliersRank.setProcPostEvalAvgScore(0.0);

        if(countProject!=0){
            extSSuppliersRank.setEngineerEvaluatAvgScore(NumberUtils.seekercentage2Double(scoureProject/countProject));
        }else extSSuppliersRank.setEngineerEvaluatAvgScore(0.0);

        supplierRankDtlRspVO.setSSuppliersRank(extSSuppliersRank);

//        SSuppliersCategoryTemplateFindRequest sSuppliersCategoryTemplateFindRequest = new SSuppliersCategoryTemplateFindRequest();
//        sSuppliersCategoryTemplateFindRequest.setCategoryId(extSSuppliersRank.getSupplierCategoryIds());
//        sSuppliersCategoryTemplateFindRequest.setTemplateType(4);
//        List<ExtSSuppliersCategoryTemplate> evaluationPerformScoresTemplateList =
//                extSSuppliersCategoryTemplateMapper.findEvaluationPerformScoresTemplateList(sSuppliersCategoryTemplateFindRequest);
//        if(CollectionUtils.isEmpty(evaluationPerformScoresTemplateList)){
//            extSSuppliersRank.setProcPostEvalPercent("50");
//            extSSuppliersRank.setEngineerEvaluatPercent("50");
//        }else{
//            for(ExtSSuppliersCategoryTemplate extSSuppliersCategoryTemplate:evaluationPerformScoresTemplateList){
//                if(extSSuppliersCategoryTemplate.getEvaluationDimension().contains("工程评估")){
//                    extSSuppliersRank.setEngineerEvaluatPercent(extSSuppliersCategoryTemplate.getScoreStandard());
//                }else{
//                    extSSuppliersRank.setProcPostEvalPercent(extSSuppliersCategoryTemplate.getScoreStandard());
//                }
//            }
//        }
        return supplierRankDtlRspVO;
    }

    private List<ExtSSuppliersRankScores> converRankScorestoExt( List<SSuppliersRankScores> sSuppliersRankScores){
	    List<ExtSSuppliersRankScores> extSSuppliersRankScores = Lists.newArrayListWithCapacity(sSuppliersRankScores.size());
	    for(SSuppliersRankScores sSuppliersRankScores1 :sSuppliersRankScores){
            ExtSSuppliersRankScores extSSuppliersRankScores1 = new ExtSSuppliersRankScores();
            BeanUtils.copyProperties(sSuppliersRankScores1,extSSuppliersRankScores1);
	        SEvaluation sEvaluation = sEvaluationService.selectById(sSuppliersRankScores1.getEvaluationId());
	        SSuppliersLastThreeAchieve sSuppliersLastThreeAchieve = sSuppliersLastThreeAchieveService.selectById(sEvaluation.getContractId());
            extSSuppliersRankScores1.setPrice(sSuppliersLastThreeAchieve.getActualContactPrice());
            extSSuppliersRankScores.add(extSSuppliersRankScores1);
	    }
	    return extSSuppliersRankScores;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void saveSupplierRankDtl(SupplierRankDtlRspVO supplierRankDtlRspVO) throws Exception {
        List<ExtSSuppliersRankScores> sSuppliersRankScores = supplierRankDtlRspVO.getSSuppliersRankScores();
//	    if(Collections3.isEmpty(sSuppliersRankScores)){
//	        throw new RuntimeException("无评估数据，不能发起定级！",new ServiceThrowable());
//        }
        LicenseUtil.INSTANCE.validate();
        ExtSSuppliersRank extSSuppliersRank=supplierRankDtlRspVO.getSSuppliersRank();
        SSuppliersRank sSuppliersRank=new SSuppliersRank();
        BeanUtils.copyProperties(extSSuppliersRank, sSuppliersRank);
        String uid = UserUtils.getCurrentUserId();
        if(StringUtils.isEmpty(sSuppliersRank.getId())){
            sSuppliersRank.setId(IdGen.uuid());
            sSuppliersRank.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_LEVEL_STATUS_1.getCode());
            sSuppliersRank.setCacheEvaluationStatus(EvaluationStatusEnum.CACHE_EVALUATION_LEVEL_STATUS_1.getCode());
            sSuppliersRank.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,true);
            sSuppliersRank.setRankYear(supplierRankDtlRspVO.getRankYear());
            //发送工程打分代办
            sendprojectScoreDeal(supplierRankDtlRspVO.getUserId(),sSuppliersRank.getSuppliersId(),sSuppliersRank.getId());

            //插入打分数据
            Date date = DateUtils.getNow();
            for(SSuppliersRankScores sSuppliersRankScores1:sSuppliersRankScores){
                sSuppliersRankScores1.setId(null);
                sSuppliersRankScores1.setBaseFeilds(uid,"",CommonConstants.DEL_FLAG_NORMAL,true);
                sSuppliersRankScores1.setSuppliersRankId(sSuppliersRank.getId());
                sSuppliersRankScores1.setEvaluationTime(date);
            }

            sSuppliersRankScoresService.insertBatch(ListObjCopyUtil.copyTo(sSuppliersRankScores,SSuppliersRankScores.class));

        }else{
            sSuppliersRank.setBaseFeilds(UserUtils.getCurrentUserId(),null,0,false);
            //sSuppliersRank.setEvaluationStatus(1);
        }

        sSuppliersRankService.insertOrUpdate(sSuppliersRank);
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void saveRankScores(SupplierRankDtlRspVO supplierRankDtlRspVO) throws Exception {
        SMyDeals sMyDeals = sMyDealsService.selectById(supplierRankDtlRspVO.getDealId());
        if(sMyDeals.getDoneFlag()==CommonConstants.DONG_FLAG){
            throw new RuntimeException("重复提交",new ServiceThrowable());
        }
        String uid = UserUtils.getCurrentUserId();
        //更新打分数据
        List<ExtSSuppliersRankScores> sSuppliersRankScores = supplierRankDtlRspVO.getSSuppliersRankScores();
        sSuppliersRankScoresService.updateBatchById(ListObjCopyUtil.copyTo(sSuppliersRankScores,SSuppliersRankScores.class));
        Double totalPoint = 0d;
        int i = 0;
        for(SSuppliersRankScores sSuppliersRankScores1:sSuppliersRankScores){
            totalPoint+=sSuppliersRankScores1.getEvaluationScore();
            i++;
        }
        SSuppliersRank sSuppliersRank = new SSuppliersRank();
        sSuppliersRank.setId(sMyDeals.getSubRelatedId());
        sSuppliersRank.setEngineerEvaluatAvgScore(NumberUtils.seekercentage2Double(totalPoint/i));
        sSuppliersRankService.updateById(sSuppliersRank);

        sMyDealsService.doneById(supplierRankDtlRspVO.getDealId());
    }

    public void sendprojectScoreDeal(String userId,String supplierId,String rankId){
        SMyDeals sMyDeals = new SMyDeals();
        String supplierName = sSuppliersService.selectById(supplierId).getCompanyName();
        SCommentConfig sc = sCommentConfigService.getByCode(CommentConfigEnum.ENGINEERING_EVALUATION_SCORE_ADD_DEAL.getCode());
        sMyDeals.setDealTitle( MessageFormat.format(sc.getConfigValue(), supplierName));
        sMyDeals.setUserId(userId);
        sMyDeals.setDealType(1);
        sMyDeals.setDealSubType(MyDealSubTypeEnum.SUPPLIERS_EVALUATION.getCode());
        sMyDeals.setActionType(ActionTypeEnum.SUPPLIERS_EVALUATION_ENGINEERING_SCORE.getCode());
        sMyDeals.setRelatedId(supplierId);
        sMyDeals.setSubRelatedId(rankId);
        sMyDeals.setDoneFlag(CommonConstants.UNDONG_FLAG);

        sMyDeals.setBaseFeilds(UserUtils.getCurrentUserId(),"",CommonConstants.DEL_FLAG_NORMAL,true);
        sMyDeals.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);

        sMyDealsService.insert(sMyDeals);
    }

    /***
     * 生成履约过程评估
     */
    @Override
    public void generateEvaluationProcesses(int genType) {
//        EvaluationTypeEnum.EVALUATION_MIDDLE_YEAR_1
//        EvaluationTypeEnum.EVALUATION_END_YEAR_2
        Integer year = Integer.valueOf(DateUtils.format(DateUtils.getNow(),"yyyy"));
        List<SSuppliersLastThreeAchieve> sSuppliersLastThreeAchieves = sSuppliersLastThreeAchieveService.selectValidData();
        List<SEvaluation> data = Lists.newArrayListWithCapacity(sSuppliersLastThreeAchieves.size());

        for(SSuppliersLastThreeAchieve sSuppliersLastThreeAchieve:sSuppliersLastThreeAchieves){
            String supplierCategoryIds = "";
            if(StringUtils.isNotEmpty(sSuppliersLastThreeAchieve.getSuppliersId())){
                SSuppliers sSuppliers = sSuppliersService.getById(sSuppliersLastThreeAchieve.getSuppliersId());
                if(sSuppliers!=null){
                    supplierCategoryIds = sSuppliers.getSupplierServiceCategoryIds();
                }
            }

            SEvaluation sEvaluation = new SEvaluation();
            sEvaluation.setEvaluationStatus(1);
            sEvaluation.setBaseFeilds("","",CommonConstants.DEL_FLAG_NORMAL,true);
            sEvaluation.setEvaluationType(1);
            sEvaluation.setEvaluationSubType(genType);
            sEvaluation.setSupplierCategoryIds(supplierCategoryIds);
            sEvaluation.setContractId(sSuppliersLastThreeAchieve.getId());
            sEvaluation.setContractName(sSuppliersLastThreeAchieve.getContactName());
            sEvaluation.setSupplierId(sSuppliersLastThreeAchieve.getSuppliersId());
            sEvaluation.setRegionalCompanyIds(sSuppliersLastThreeAchieve.getRegionalCompanyId());
            sEvaluation.setProjectIds(sSuppliersLastThreeAchieve.getCooperativeProjectId());
            sEvaluation.setEvaluationYear(year);
            sEvaluation.setHandleUserId("");
            sEvaluation.setEvaluationDesc("");
            data.add(sEvaluation);
        }
        sEvaluationService.insertBatch(data);
    }


    @Override
    public ExtSEvaluationTemplate getEvaluationTemlById(String id) {
        ExtSEvaluationTemplate extSEvaluationTemplate = new ExtSEvaluationTemplate();
        SEvaluationTemplate sEvaluationTemplate = sEvaluationTemplateService.selectById(id);
        BeanUtils.copyProperties(sEvaluationTemplate,extSEvaluationTemplate);
        extSEvaluationTemplate.setChilds(sEvaluationTemplateDetailsService.getByParentId(id));
        return extSEvaluationTemplate;
    }
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void saveEvaluationTeml(ExtSEvaluationTemplate extSEvaluationTemplate) {
        String userId = UserUtils.getCurrentUserId();
        if(StringUtils.isNotEmpty(extSEvaluationTemplate.getId())){
            sEvaluationTemplateService.updateById(extSEvaluationTemplate);
            SEvaluationTemplateDetails where = new SEvaluationTemplateDetails();
            where.setEvaluationTemplateId(extSEvaluationTemplate.getId());
            sEvaluationTemplateDetailsService.delete(new EntityWrapper<>(where));
        }else{
            extSEvaluationTemplate.setBaseFeilds(userId,"",CommonConstants.DEL_FLAG_NORMAL,true);
            sEvaluationTemplateService.insert(extSEvaluationTemplate);
        }
        Integer totalWeight = 0;
        for(SEvaluationTemplateDetails sEvaluationTemplateDetails :extSEvaluationTemplate.getChilds()){
            if(sEvaluationTemplateDetails.getEvaluationWeight()==null){
                throw new RuntimeException("模板权值设置异常",new ServiceThrowable());
            }else{
                totalWeight +=Integer.parseInt(sEvaluationTemplateDetails.getEvaluationWeight());
            }
            sEvaluationTemplateDetails.setId(null);
            sEvaluationTemplateDetails.setEvaluationTemplateId(extSEvaluationTemplate.getId());
            sEvaluationTemplateDetails.setBaseFeilds(userId,"",CommonConstants.DEL_FLAG_NORMAL,true);
        }
        if(totalWeight!=100)
            throw new RuntimeException("模板权值总和不等于100！",new ServiceThrowable());
        sEvaluationTemplateDetailsService.insertBatch(extSEvaluationTemplate.getChilds());
    }

    @Override
    public List<SEvaluationTemplate> getSEvaluationTemplateByEntity(SEvaluationTemplate sEvaluationTemplate) {
        sEvaluationTemplate.setDelFlag(CommonConstants.DEL_FLAG_NORMAL);
        EntityWrapper<SEvaluationTemplate> sEvaluationTemplateEntityWrapper = new EntityWrapper<>(sEvaluationTemplate);
        if(StringUtils.isNotEmpty(sEvaluationTemplate.getTemplateName())){
            sEvaluationTemplate.setTemplateName(null);
            sEvaluationTemplateEntityWrapper.like("template_name",sEvaluationTemplate.getTemplateName());
        }
        LicenseUtil.INSTANCE.validate();
        return sEvaluationTemplateService.selectList(sEvaluationTemplateEntityWrapper);
    }

    @Override
    public ExtSEvaluation getLaunchEvaluationTeml(String id) {
        ExtSEvaluation extSEvaluation = new ExtSEvaluation();
        List<SEvaluationTemplateDetails> sEvaluationTemplateDetails = sEvaluationTemplateDetailsService.getByParentId(id);
        extSEvaluation.setExtSEvaluationPersonList(convertSETemplateDetails2ExtSEvaluationPerson(sEvaluationTemplateDetails));
        extSEvaluation.setExtSEvaluationPerformScoresList(convertSETemplateDetails2ExtSEPerformScores(sEvaluationTemplateDetails));
        return extSEvaluation;
    }

    public List<ExtSEvaluationPerformScores> convertSETemplateDetails2ExtSEPerformScores(
            List<SEvaluationTemplateDetails> sEvaluationTemplateDetails) {
        if (sEvaluationTemplateDetails == null) return null;
        List<ExtSEvaluationPerformScores> list = Lists.newArrayListWithCapacity(sEvaluationTemplateDetails.size());

        for (SEvaluationTemplateDetails vo : sEvaluationTemplateDetails) {
            ExtSEvaluationPerformScores entity = new ExtSEvaluationPerformScores();
            entity.setEvaluationLatitude(vo.getEvaluationLatitude());
            entity.setEvaluationIndicator(vo.getEvaluationIndicator());
            entity.setEvaluationWeight(vo.getEvaluationWeight());
            entity.setScoreStandard(vo.getScoreStandard());
            entity.setEvaluatorUserId(vo.getEvaluatorUserId());
            entity.setEvaluationDepartmentId(vo.getEvaluationDepartmentId());
            list.add(entity);
        }
        return list;
    }

    public List<ExtSEvaluationPerson> convertSETemplateDetails2ExtSEvaluationPerson(
            List<SEvaluationTemplateDetails> sEvaluationTemplateDetails) {
        if (sEvaluationTemplateDetails == null) return null;
        Map<String,String> map = Maps.newHashMap();
        List<ExtSEvaluationPerson> extSEvaluationPersonList = Lists.newArrayList();
        for (SEvaluationTemplateDetails vo : sEvaluationTemplateDetails) {
            if(map.get(vo.getEvaluationDepartmentId())==null){
                ExtSEvaluationPerson entity = new ExtSEvaluationPerson();
                entity.setDepartmentId(vo.getEvaluationDepartmentId());
                extSEvaluationPersonList.add(entity);
                map.put(vo.getEvaluationDepartmentId(),vo.getEvaluationDepartmentId());
            }
        }
        LicenseUtil.INSTANCE.validate();
        return extSEvaluationPersonList;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public String initiateApprovalSupplierRank(InitiateApprovalSupplierRankReqVo vo) {
        String rankIds = vo.getSuppliersRankIds();
        SessionUserVo userVo = UserUtils.getCurrentUserVo();
        if(userVo == null){
            throw new RuntimeException("未获取到当前操作人信息，请登录后重试");
        }
        String userId = userVo.getEmployeeID();
        if(StringUtils.isEmpty(rankIds)){
            throw new RuntimeException("请选择至少一条数据",new ServiceThrowable());
        }
        LicenseUtil.INSTANCE.validate();
        SSuppliersRankAudits sSuppliersRankAudits = null;
        String[] rankIdsArr = rankIds.split(",");
        boolean result = sSuppliersRankService.updateStatusByIds(null,
                EvaluationStatusEnum.EVALUATION_LEVEL_STATUS_2.getCode(),rankIdsArr);
        if(result){
            sSuppliersRankAudits = new SSuppliersRankAudits();
            sSuppliersRankAudits.setAuditsCode(UUID.randomUUID().toString());
            sSuppliersRankAudits.setSuppliersRankIds(rankIds);
            sSuppliersRankAudits.setSendTime(DateUtils.getNow());
            sSuppliersRankAudits.setBaseFeilds(userId,"",CommonConstants.DEL_FLAG_NORMAL,true);
            sSuppliersRankAuditsService.insert(sSuppliersRankAudits);
            List<SSuppliersRankAuditsDetail> sSuppliersRankAuditsDetails = Lists.newArrayListWithCapacity(rankIdsArr.length);
            for(String rankId:rankIdsArr){
                SSuppliersRankAuditsDetail sSuppliersRankAuditsDetail = new SSuppliersRankAuditsDetail();
                sSuppliersRankAuditsDetail.setSuppliersRankAuditsId(sSuppliersRankAudits.getId());
                sSuppliersRankAuditsDetail.setSuppliersRankId(rankId);
                sSuppliersRankAuditsDetail.setEvaluationStatus((EvaluationStatusEnum.CACHE_EVALUATION_LEVEL_STATUS_1.getCode()));
                sSuppliersRankAuditsDetail.setBaseFeilds(userId,"",CommonConstants.DEL_FLAG_NORMAL,true);
                sSuppliersRankAuditsDetails.add(sSuppliersRankAuditsDetail);
            }
            sSuppliersRankAuditsDetailService.insertBatch(sSuppliersRankAuditsDetails);
        }else{
            throw new RuntimeException("请确认选择的数据都是待审批的",new ServiceThrowable());
        }

        //MBS流程审批
        Map<String, Object> mapParams = new HashMap<String, Object>();
        mapParams.put("CURRENT_USER_ID", userId);
        // 当前人账号
        mapParams.put("CURRENT_USER_NAME", userVo.getUserName());
        mapParams.put("RELATE_ID", sSuppliersRankAudits.getId());
        SessionUserVo user = UserUtils.getCurrentUserVo();
        if(user != null){
            mapParams.put("ORG_CODE", user.getCompanyCode());
            mapParams.put("ORG_NAME", user.getsCompanyName());
            mapParams.put("EMPLOYEE_CODE", user.getEmployeeID());
        }else{
            throw new RuntimeException("获取不到用户信息");
        }
        Map<String,Object> mapBpmParams = bpmUtil.invokeApprovalFlow(mapParams, AbutmentSubTypeEnum.RANK_APPROVE.getCode());
        Boolean isSuccess = (Boolean)mapBpmParams.get("IS_SUCCESS");
        String mbsUrl = (String)mapBpmParams.get("MBS_URL");
        if(isSuccess == false) {
            throw new RuntimeException("BPM定级审核对接失败");
        }

        SHistoryComment sHistoryComment = new SHistoryComment();
        sHistoryComment.setBaseFeilds(userId,"",0,true);
        sHistoryComment.setModelType(HistoryCommentModelTypeEnum.HistoryCommentModelType29.getCode()); //供方信息审核历程
        sHistoryComment.setRelatedId(sSuppliersRankAudits.getId());
        sHistoryComment.setSubRelatedId(sSuppliersRankAudits.getId());
        sHistoryComment.setCommentType(HistoryCommentTypeEnum.INTRANET.getCode());  //内外网共用
        sHistoryComment.setNodeName("发起定级审批");
        sHistoryComment.setActionName("发起定级审批");
        sHistoryComment.setCommentUrl(mbsUrl);
        sHistoryCommentService.insert(sHistoryComment);
        return mbsUrl;
    }

    @Override
    public ApprovalSupplierRankDtlVo approvalSupplierRankDtl(String id) {
        ApprovalSupplierRankDtlVo approvalSupplierRankDtlVo = new ApprovalSupplierRankDtlVo();
        ExtSSuppliersRankAudits sSuppliersRankAudits = sSuppliersRankAuditsService.getExtById(id);
        approvalSupplierRankDtlVo.setSendTime(sSuppliersRankAudits.getSendTime());
        approvalSupplierRankDtlVo.setData(sSuppliersRankAudits.getExtSSuppliersRankAuditsDetails());
        return approvalSupplierRankDtlVo;
    }

    @Override
    public boolean approvalSupplierRank(SupplierRankApprovalResultVo vo) {
        try{
            SSuppliersRankAuditsDetail sSuppliersRankAuditsDetail = new SSuppliersRankAuditsDetail();
            sSuppliersRankAuditsDetail.setId(vo.getId());
            sSuppliersRankAuditsDetail.setEvaluationStatus(vo.getAgreeFlag()==1?EvaluationStatusEnum.CACHE_EVALUATION_LEVEL_STATUS_2.getCode():EvaluationStatusEnum.CACHE_EVALUATION_LEVEL_STATUS_3.getCode());
            return sSuppliersRankAuditsDetailService.updateById(sSuppliersRankAuditsDetail);
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public List<ExtSEvaluationImproveHis> getImproveHistory(String evaluationId) {
        return extSEvaluationImproveHisMapper.findAllBySEvaluaId(evaluationId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void submitImproveDetail(SEvaluaImproveVO vo) {
        SEvaluation update = new SEvaluation();
        update.setId(vo.getEvaluationId());
        update.setEvaluationScore(vo.getImproveScores());
        update.setImproveFlag(1);
        sEvaluationMapper.updateById(update);
        String userId = UserUtils.getCurrentUserId();

        SEvaluationImproveHis sEvaluationImproveHis = new SEvaluationImproveHis();
        sEvaluationImproveHis.setBaseFeilds(userId,"",0,true);
        sEvaluationImproveHis.setEvaluationId(vo.getEvaluationId());
        sEvaluationImproveHis.setOrginValue(vo.getOriScores());
        sEvaluationImproveHis.setImpovedValue(vo.getImproveScores());
        sEvaluationImproveHis.setImpoveUserId(userId);
        sEvaluationImproveHisMapper.insert(sEvaluationImproveHis);

        LicenseUtil.INSTANCE.validate();
        if(vo.getAttachments()!=null)
            for(SAttachment sAttachment:vo.getAttachments()){
                sAttachment.setBaseFeilds(userId,"",0,true);
                sAttachment.setFormId(sEvaluationImproveHis.getId());
                sAttachment.setAttachmentType(AttachmentTypeEnum.ATTACHMENT_TYPE_101.getCode());
                sAttachmentMapper.insert(sAttachment);
            }
    }

    @Override
    public Page<ExtSSuppliersLastThreeAchieve> selectEvaluationLastContact(Page<ExtSSuppliersLastThreeAchieve> page, ExtSSuppliersLastThreeAchieve extSSuppliersLastThreeAchieve) {
        try{
            extSSuppliersLastThreeAchieve.setSourceType(2);
            List<ExtSSuppliersLastThreeAchieve> data = sSuppliersLastThreeAchieveService.findExtList(page, extSSuppliersLastThreeAchieve);
            page.setRecords(data);
            return page;
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    public void approvalSupplierRankFinal(SupplierRankApprovalResultVo vo) {
        SSuppliersRankAuditsDetail sSuppliersRankAuditsDetail = new SSuppliersRankAuditsDetail();
        sSuppliersRankAuditsDetail.setSuppliersRankAuditsId(vo.getId());
        EntityWrapper entityWrapper  = new EntityWrapper(sSuppliersRankAuditsDetail);
        List<SSuppliersRankAuditsDetail> list = sSuppliersRankAuditsDetailService.selectList(entityWrapper);
        List<SSuppliersRank> sSuppliersRanks = Lists.newArrayListWithCapacity(list.size());
        for(SSuppliersRankAuditsDetail sSuppliersRankAuditsDetail1:list){
            SSuppliersRank sSuppliersRank = new SSuppliersRank();
            sSuppliersRank.setId(sSuppliersRankAuditsDetail1.getSuppliersRankId());
            if(vo.getAgreeFlag()==2){
                if(vo.getAgreeFlag()==EvaluationStatusEnum.CACHE_EVALUATION_LEVEL_STATUS_3.getCode()){
                    sSuppliersRank.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_LEVEL_STATUS_3.getCode());
                    SSuppliersRank sSuppliersRankDb = sSuppliersRankService.selectById(sSuppliersRankAuditsDetail1.getSuppliersRankId());
                    SSuppliers sSuppliers = new SSuppliers();
                    sSuppliers.setId(sSuppliersRankDb.getSuppliersId());
                    sSuppliers.setStarLevel(sSuppliersRankDb.getStarLevel());
                    sSuppliersService.updateById(sSuppliers);
                }else {
                    sSuppliersRank.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_LEVEL_STATUS_4.getCode());
                }
            }else{
                sSuppliersRank.setEvaluationStatus(EvaluationStatusEnum.EVALUATION_LEVEL_STATUS_1.getCode());
            }

            sSuppliersRanks.add(sSuppliersRank);
        }
        LicenseUtil.INSTANCE.validate();
        sSuppliersRankService.updateBatchById(sSuppliersRanks);
    }
}
